package com.heima.wemedia.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.heima.api.feign.ApArticleFeignClient;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.wemedia.service.WmNewsAuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 延迟交换
 *
 * @Author mr.chen
 * @Date 2025/6/28 17:24
 */
@Component
@Slf4j
public class DelayListener {

    @Autowired
    private WmNewsAuditService wmNewsAuditService;

    @Autowired
    private ApArticleFeignClient apArticleFeignClient;

    //文章发布监听器
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = WmNewsMessageConstants.WM_NEWS_DELAY_DIRECT_QUEUE,durable = "true"),
            exchange = @Exchange(name = WmNewsMessageConstants.WM_NEWS_DELAY_DIRECT,delayed = "true",type = ExchangeTypes.DIRECT),
            key = WmNewsMessageConstants.WM_NEWS_DELAY_DIRECT_ROUTINGKEY
    ))
    public void getMessage(String message){
        Map map = JSONUtil.toBean(message, Map.class);
        log.error("数据:{}",map);
        ArticleDto articleDto = BeanUtil.toBean(map.get("ArticleDto"), ArticleDto.class);
        WmNews wmNews = BeanUtil.toBean(map.get("wmNews"), WmNews.class);
        wmNews.setStatus((short) 9);
        wmNews.setReason("发布成功");
        wmNewsAuditService.updateById(wmNews);

        //添加app文章
        ResponseResult<Long> saveResult = apArticleFeignClient.save(articleDto);
        Long articleId = saveResult.getData(); // 获取 articleId
        wmNews.setArticleId(articleId);
        wmNewsAuditService.updateById(wmNews);

    }
}
